package com.explore.demo.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

/**
 * 文件有关的工具类
 * @author gaolainan
 */
@Component
public class FileUtils
{

    @Value("${file.uploadUrl}")
    private String uploadFilePath;

    /**
     * 上传文件的接口
     *
     * @param file
     * @return
     */
    public String saveFile(MultipartFile file)
    {
        if (file.isEmpty())
        {
            return "";
        }
        // 获取上传文件原来的名称
        String filename = file.getOriginalFilename();
        String filePath = uploadFilePath;
        File temp = new File(filePath);
        if (!temp.exists())
        {
            temp.mkdirs();
        }


        String finalPath = filePath + filename;
        System.out.println(finalPath);
        File localFile = new File(filePath + filename);
        try
        {
            // 把上传的文件保存至本地
            file.transferTo(localFile);
            System.out.println(file.getOriginalFilename() + " 上传成功！");
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return "";
        }

        return finalPath;
    }


}
